import { Dimensions, PixelRatio, ScaledSize, useWindowDimensions } from 'react-native';
import { useEffect, useState } from 'react';

// 基准设计尺寸
// 手机版设计尺寸参考：360 x 640 (DPI 320)
// 平板版设计尺寸参考：768 x 1024 (DPI 240)
const DEFAULT_PHONE_BASE_WIDTH = 360;
const DEFAULT_PHONE_BASE_HEIGHT = 640;
const DEFAULT_TABLET_BASE_WIDTH = 768;
const DEFAULT_TABLET_BASE_HEIGHT = 1024;
const DEFAULT_PHONE_BASE_FONT_SIZE = 14;
const DEFAULT_TABLET_BASE_FONT_SIZE = 16;

// 平板宽度判断阈值
const TABLET_WIDTH_THRESHOLD = 600;

// 获取当前设备信息
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window');
const DEVICE_PIXEL_RATIO = PixelRatio.get();

// 判断当前设备是否为平板
export const isTablet = (): boolean => {
  return SCREEN_WIDTH >= TABLET_WIDTH_THRESHOLD;
};

// 获取当前设备基准尺寸
export const getBaseSize = () => {
  if (isTablet()) {
    return {
      baseWidth: DEFAULT_TABLET_BASE_WIDTH,
      baseHeight: DEFAULT_TABLET_BASE_HEIGHT,
      baseFontSize: DEFAULT_TABLET_BASE_FONT_SIZE
    };
  }
  return {
    baseWidth: DEFAULT_PHONE_BASE_WIDTH,
    baseHeight: DEFAULT_PHONE_BASE_HEIGHT,
    baseFontSize: DEFAULT_PHONE_BASE_FONT_SIZE
  };
};

// 响应式宽度计算
export const wp = (widthPercent: number): number => {
  // 直接使用参数值，不做额外转换
  return PixelRatio.roundToNearestPixel(widthPercent);
};

// 响应式高度计算
export const hp = (heightPercent: number): number => {
  // 直接使用参数值，不做额外转换
  return PixelRatio.roundToNearestPixel(heightPercent);
};

// 响应式字体大小计算
export const fs = (fontSize: number): number => {
  // 根据设备类型选择合适的字体大小
  if (isTablet()) {
    // 平板上稍微放大
    return PixelRatio.roundToNearestPixel(fontSize * 1.15);
  }
  // 手机保持原样
  return PixelRatio.roundToNearestPixel(fontSize);
};

// 横竖屏监听 Hook
export const useOrientation = () => {
  const [orientation, setOrientation] = useState<'PORTRAIT' | 'LANDSCAPE'>(
    SCREEN_WIDTH < SCREEN_HEIGHT ? 'PORTRAIT' : 'LANDSCAPE'
  );

  useEffect(() => {
    const handleOrientationChange = ({ window }: { window: ScaledSize }) => {
      const isPortrait = window.width < window.height;
      setOrientation(isPortrait ? 'PORTRAIT' : 'LANDSCAPE');
    };

    const subscription = Dimensions.addEventListener('change', handleOrientationChange);

    return () => {
      // React Native 0.65以上使用remove，低版本使用removeEventListener
      if (subscription?.remove) {
        subscription.remove();
      }
    };
  }, []);

  return orientation;
};

// 响应式上下文 Hook
export const useResponsive = () => {
  const dimensions = useWindowDimensions();
  const orientation = useOrientation();
  const tablet = dimensions.width >= TABLET_WIDTH_THRESHOLD;

  return {
    wp,
    hp,
    fs,
    orientation,
    isTablet: tablet,
    width: dimensions.width,
    height: dimensions.height,
    pixelRatio: DEVICE_PIXEL_RATIO
  };
}; 